package base;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Locale;
import java.util.TimeZone;

public class TestMain {
    /* 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险，建议在配置文件或者环境变量中密文存
放，使用时解密，确保安全；
本示例以ak和sk保存在环境变量中为例，运行本示例前请先在本地环境中设置环境变量YOUR_AK和
YOUR_SK。*/
    public static String accessKey = "OJIPOAKE68GSR9VDQVBU"; //取值为获取的AK
    public static String securityKey = "x29BpkBn1wwxghDv97LLM6lOoH1Fi3k3rAYufNaV"; //取值为获取的SK

    public static void main(String[] str) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        listAllMyBuckets();
    }

    public static String formatDate(long time)
    {
        DateFormat serverDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",
                Locale.ENGLISH);
        serverDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return serverDateFormat.format(time);
    }

    public static String signWithHmacSha1(String sk, String canonicalString) throws
            UnsupportedEncodingException {
        System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZ");
        System.out.println(canonicalString);
        System.out.println("=============");
        try {
            SecretKeySpec signingKey = new SecretKeySpec(sk.getBytes("UTF-8"), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            return Base64.getEncoder().encodeToString(mac.doFinal(canonicalString.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void listAllMyBuckets() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        // 创建一个不验证证书链的 SSLContext
        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (chain, authType) -> true) // 接受所有证书
                .build();

        // 使用创建的 SSLContext 和 NoopHostnameVerifier 构建 HttpClient
        CloseableHttpClient httpClient =  HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();

        String requesttime = formatDate(System.currentTimeMillis());
        HttpGet httpGet = new HttpGet("https://obsv3.smw-b-1.rtzby.com");
        httpGet.addHeader("Date", requesttime);

        /** 根据请求计算签名**/
        String contentMD5 = "";
        String contentType = "";
        String canonicalizedHeaders = "";
        String canonicalizedResource = "/";

        // Content-MD5 、Content-Type 没有直接换行， data格式为RFC 1123，和请求中的时间一致
        String canonicalString = "GET" + "\n" + contentMD5 + "\n" + contentType + "\n" + requesttime + "\n"
                + canonicalizedHeaders + canonicalizedResource;
        System.out.println("StringToSign:[" + canonicalString + "]");
        String signature = null;
        try {
            signature = signWithHmacSha1(securityKey, canonicalString);

            // 增加签名头域 Authorization: OBS AccessKeyID:signature
            httpGet.addHeader("Authorization", "OBS " + accessKey + ":" + signature);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

            // 打印发送请求信息和收到的响应消息
            System.out.println("Request Message:");
            System.out.println(httpGet.getRequestLine());
            for (Header header : httpGet.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }
            System.out.println("Response Message:");
            System.out.println(httpResponse.getStatusLine());
            for (Header header : httpResponse.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            reader.close();
            // print result
            System.out.println(response.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
